package com.etop.jansing.controller;

import com.etop.jansing.dto.ResourceDto;
import com.etop.jansing.entities.Role;
import com.etop.jansing.service.ResourceService;
import com.etop.jansing.service.RoleService;
import com.etop.jansing.util.CommonUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * Created by jansing on 2015/10/25.
 */
@Controller
@RequestMapping("admin/role")
@RequiresRoles("admin")
public class RoleController extends BaseController {
    @Resource
    private RoleService roleService;
    @Resource
    private ResourceService resourceService;

    /**
     * 注入角色信息。<br/>
     * 这个方法会在请求进入该控制器的某个方法前调用，<br/>
     * 比如修改角色：在进入edit()--POST 前会执行此方法返回一个role，然后再将表单的数据放入这个role<br/>
     *
     * @param tempId
     * @return
     */
    @ModelAttribute("role")
    public Role get(@RequestParam(required = false, value = "id") String tempId) {
        try {
            Long id = Long.parseLong(tempId);
            if (id != null && id > 0) {
                return roleService.getById(id);
            } else {
                return new Role();
            }
        } catch (NumberFormatException e) {
            return new Role();
        }
    }

    /**
     *
     * @param role
     * @param model
     * @return
     */
    @RequiresPermissions("role:list")
    @RequestMapping(value = "/list", produces = "text/html;charset=utf-8")
    public String list(@ModelAttribute("role") Role role, Model model) {
        List<Role> roleList = roleService.getAllRoles();
        model.addAttribute("roleList", roleList);
        return "admin/role/list";
    }

    @RequiresPermissions("role:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String editRole(Model model, @ModelAttribute("role") Role role) {
        ResourceDto rootResourceDto = resourceService.getRootResource(Arrays.asList(role));
        model.addAttribute("role", role);
        model.addAttribute("rootResourceDto", rootResourceDto);
        return "/admin/role/edit";
    }

    @RequiresPermissions("role:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.POST)
    public String saveRole(@ModelAttribute(value = "role") Role role, HttpServletRequest request, Model model) throws Exception {
        String oldName = request.getParameter("oldName");
        //与已删除的角色也不能同名
        if (!oldName.equals(role.getName()) && roleService.getByNameIgnoreValid(role.getName()) != null) {
            log.error("-->该角色名已存在");
            role.setName(oldName);
            return editRole(model, role);
        }
        String[] rpids = request.getParameterValues("rpids");
        roleService.saveOrUpdate(role, rpids);
        return "redirect:/admin/role/list";
    }

    /**
     * 如果某个用户拥有该角色，则拒绝删除；删除角色的同时将其资源权限对清除
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("role:delete")
    @RequestMapping(value = "/delete/{id}", produces = "text/html;charset=utf-8")
    public String deleteRole(@PathVariable("id") long id, Model model) {
        if (roleService.isUsing(id)) {
            log.error("-->该角色已被使用，请先在用户中解除对该角色的使用");
        } else {
            roleService.delete(id);
        }
        return "redirect:/admin/role/list";
    }
}
